package com.example.testapp.domain.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.annotation.NonNull
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

/**
 * 图片处理工具类，用于OCR识别等图片处理功能
 */
object ImageProcessUtil {
    private const val TAG = "ImageProcessUtil"
    
    // 模拟OCR处理的延迟时间（实际项目中应对接真实OCR服务）
    private const val MIN_PROCESS_TIME_MS = 1000
    private const val MAX_PROCESS_TIME_MS = 3000
    
    /**
     * 回调接口
     */
    interface ImageProcessCallback {
        /**
         * 处理成功回调
         * @param result 识别结果
         */
        fun onSuccess(result: OcrResult)
        
        /**
         * 处理失败回调
         * @param errorCode 错误代码
         * @param errorMessage 错误信息
         */
        fun onFailure(errorCode: String, errorMessage: String)
    }
    
    /**
     * OCR识别结果
     */
    class OcrResult private constructor(
        val text: String,
        val amount: Int,
        val date: String,
        val category: String,
        val description: String
    ) {
        companion object {
            fun create(text: String, amount: Int, date: String, category: String, description: String): OcrResult {
                return OcrResult(text, amount, date, category, description)
            }
        }
    }
    
    /**
     * 处理图片，识别账单信息（模拟OCR）
     * @param context 上下文
     * @param imagePath 图片路径
     * @param callback 回调
     */
    @JvmStatic
    fun processImage(@NonNull context: Context, @NonNull imagePath: String, @NonNull callback: ImageProcessCallback) {
        // 检查文件是否存在
        val imageFile = File(imagePath)
        if (!imageFile.exists() || !imageFile.isFile) {
            callback.onFailure("FILE_NOT_FOUND", "Image file not found: $imagePath")
            return
        }
        
        // 检查文件是否可以解码为图像
        val options = BitmapFactory.Options().apply {
            inJustDecodeBounds = true
        }
        BitmapFactory.decodeFile(imagePath, options)
        
        if (options.outWidth <= 0 || options.outHeight <= 0) {
            callback.onFailure("INVALID_IMAGE", "Cannot decode image: $imagePath")
            return
        }
        
        // 模拟OCR处理（实际项目中应调用真实OCR API）
        val random = Random()
        val processTime = random.nextInt(MAX_PROCESS_TIME_MS - MIN_PROCESS_TIME_MS) + MIN_PROCESS_TIME_MS
        
        Handler(Looper.getMainLooper()).postDelayed({
            // 模拟90%的成功率
            if (random.nextInt(100) < 90) {
                // 生成模拟数据
                val result = generateMockResult()
                callback.onSuccess(result)
            } else {
                // 模拟错误
                callback.onFailure("OCR_FAILED", "Failed to recognize text in image")
            }
        }, processTime.toLong())
    }
    
    /**
     * 生成模拟OCR结果
     * @return 模拟OCR结果
     */
    private fun generateMockResult(): OcrResult {
        val random = Random()
        
        // 生成随机金额（10-1000元）
        val amount = (random.nextInt(990) + 10) * 100 // 单位为分
        
        // 生成随机日期（最近30天内）
        val now = System.currentTimeMillis()
        val randomTime = now - random.nextInt(30) * 24 * 60 * 60 * 1000L
        val date = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date(randomTime))
        
        // 随机选择类别
        val categories = arrayOf("餐饮", "交通", "购物", "娱乐", "住房", "医疗", "教育", "其他")
        val category = categories[random.nextInt(categories.size)]
        
        // 随机生成描述
        val descriptions = arrayOf(
            "超市购物", "午餐", "晚餐", "打车", "电影票", "水电费", "房租", "药品", "书籍",
            "衣服", "鞋子", "手机充值", "网络费用", "健身", "零食", "咖啡", "茶饮"
        )
        val description = descriptions[random.nextInt(descriptions.size)]
        
        // 假设的完整文本
        val text = "商户: 某商家名称\n" +
                  "日期: $date\n" +
                  "金额: ${amount / 100.0}元\n" +
                  "类型: $category\n" +
                  "描述: $description"
        
        return OcrResult.create(text, amount, date, category, description)
    }
} 